package com.jiepos.mpos.pay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.jiepos.mpos.common.constant.SystemConstant;

/**
 * 定时查询服务 查询结果未知的提现记录，
 * 按照5分钟、10分钟、15分钟、30分钟、1小时、2小时查询六次，
 * 若还查不到，结果不更新。
 * <p>标题: —— </p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @ProjectName:  [mpos] 
 * @Package com.jiepos.mpos.pay 
 * @author 张学涛
 * @version 1.0
 * @since 2017年10月23日下午2:53:10
 * @history（历次修订内容、修订人、修订时间等）
 */
public class WithdrawQueryService {
	
	private static final Logger _log = LoggerFactory.getLogger(WithdrawQueryService.class);
	private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(30);
	
	@Autowired
	private LogAbstractService logAbstractService;
	@Autowired
	private PayService payService;
	
	public synchronized void process() {
		_log.info("定时查询未知的提现记录");
		List<Map<String, String>> list = logAbstractService.getUnknownWithdraw();
		if (list != null && !list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {
				queryService(list.get(i));
			}
		}
	}
	
	
	private void queryService(final Map<String, String> reqMap) {
		final int[] times = { 5, 10, 15, 30, 60, 120 };
		fixedThreadPool.execute(new Runnable() {
			public void run() {
				String apply_no = reqMap.get("apply_no");
				if (apply_no != null && !apply_no.equals("")) {
					for (int i = 0; i < times.length; i++) {
						try {
							TimeUnit.MINUTES.sleep(times[i]);
							//TimeUnit.SECONDS.sleep(times[i]);
							Map<String, String> resqMap = payService.withdrawQuery(apply_no);							
							_log.info("未知交易=[{}]主动查询,查询次数为=[{}],响应数据为=[{}]", apply_no, i, resqMap);
							if(SystemConstant.RSPCODE_SUCCESS.equals(resqMap.get("rsp_code"))){								
								Map<String, String> params=new HashMap<String, String>();									
								params.put("apply_no", apply_no);								
								logAbstractService.update(params, resqMap);
								break;
							}							
						} catch (Exception e) {
							_log.error("未知交易[{}]主动查询发生异常[{}]", apply_no, e);
							continue;
						}
					}
				}
			}
		});
	}

}
